package com.folderit.apps.rooms;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.folderit.apps.rooms.data.RoomsContract;
import com.folderit.apps.rooms.data.RoomsContract.ReservationEntry;
import com.folderit.apps.rooms.data.RoomsContract.RoomEntry;
import com.folderit.apps.rooms.data.RoomsContract.UserEntry;

import java.text.SimpleDateFormat;

/**
 * Created by César on 25/12/2014.
 */
public class ReservationDetailsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String LOG_TAG = ReservationDetailsFragment.class.getSimpleName();
    private static final int DETAIL_LOADER = 0;

    private int mReservation;

    private static final String[] RESERVATION_COLUMNS = {
            ReservationEntry.TABLE_NAME + "." + ReservationEntry._ID,
            ReservationEntry.COLUMN_EVENT_TITLE,
            ReservationEntry.COLUMN_BEGIN,
            ReservationEntry.COLUMN_END,
            ReservationEntry.COLUMN_CREATED,
            UserEntry.COLUMN_NAME,
            UserEntry.COLUMN_PHONE_NUMBER,
            RoomEntry.COLUMN_ROOM_NAME,
            UserEntry.COLUMN_EMAIL
    };

    // Column indexes
    private static final int COL_RESERVATION_ID = 0;
    private static final int COL_EVENT_TITLE = 1;
    private static final int COL_RESERVATION_BEGIN = 2;
    private static final int COL_RESERVATION_END = 3;
    private static final int COL_RESERVATION_CREATED = 4;
    private static final int COL_USER_NAME = 5;
    private static final int COL_USER_PHONE_NUMBER = 6;
    private static final int COL_ROOM_NAME = 7;
    private static final int COL_USER_EMAIL = 8;

    // Views
    private TextView mEventTitleView;
    private TextView mRoomView;
    private TextView mDateView;
    private TextView mBeginEndDurationView;
    private TextView mCreatedView;

    // Field with user info to build intents for call and sending email
    private String mUserName;
    private String mUserPhoneNumber;
    private String mUserEmail;

    public ReservationDetailsFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(ReservationDetailsActivity.SELECTED_RESERVATION_KEY, mReservation);
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle arguments = getArguments();
        if (arguments != null) {
            mReservation = arguments.getInt(ReservationDetailsActivity.SELECTED_RESERVATION_KEY);
        }

        if (savedInstanceState != null && mReservation == 0) {
            mReservation = savedInstanceState.getInt(ReservationDetailsActivity.SELECTED_RESERVATION_KEY);
        }

        View rootView = inflater.inflate(R.layout.fragment_reservation_details, container, false);
        mEventTitleView = (TextView) rootView.findViewById(R.id.reservation_details_event_title_textview);
        mRoomView = (TextView) rootView.findViewById(R.id.reservation_details_room_name_textview);
        mDateView = (TextView) rootView.findViewById(R.id.reservation_details_date_textview);
        mBeginEndDurationView = (TextView) rootView.findViewById(R.id.reservation_details_begin_end_duration_textview);
        mCreatedView = (TextView) rootView.findViewById(R.id.reservation_details_created_textview);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle arguments = getArguments();
        if ((arguments != null && arguments.containsKey(ReservationDetailsActivity.SELECTED_RESERVATION_KEY)) || mReservation > 0) {
            getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.reservationdetailsfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_call_user) {
            startActivity(createCallUserIntent());
            return true;
        }
        if (id == R.id.action_send_email) {
            startActivity(createSendMailIntent());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private Intent createCallUserIntent() {
        String uri = "tel:" + mUserPhoneNumber;

        Intent callIntent = new Intent(Intent.ACTION_DIAL);
        callIntent.setData(Uri.parse(uri));

        return callIntent;
    }

    private Intent createSendMailIntent() {
        Intent sendMailIntent = new Intent(Intent.ACTION_SEND);
        sendMailIntent.setData(Uri.parse("mailto:"));
        sendMailIntent.setType("text/plain");
        sendMailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{ mUserEmail });
        sendMailIntent.putExtra(Intent.EXTRA_SUBJECT, "About your reservation");

        return sendMailIntent;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            mReservation = savedInstanceState.getInt(ReservationDetailsActivity.SELECTED_RESERVATION_KEY);
        }

        Bundle arguments = getArguments();
        if (mReservation > 0 || (arguments != null && arguments.containsKey(ReservationDetailsActivity.SELECTED_RESERVATION_KEY))) {
            getLoaderManager().initLoader(DETAIL_LOADER, null, this);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        Uri reservationUri = ReservationEntry.buildReservationUri(mReservation);

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(
                getActivity(),
                reservationUri,
                RESERVATION_COLUMNS,
                null,
                null,
                null
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null && data.moveToFirst()) {

            Context context = getActivity();

            String eventTitle = data.getString(COL_EVENT_TITLE);
            mEventTitleView.setText(eventTitle);

            String roomName = data.getString(COL_ROOM_NAME);
            mRoomView.setText(String.format(
                    getActivity().getString(R.string.reservation_details_on_room),
                    roomName));

            // Set the date of the reservation using the begin time
            String begin = data.getString(COL_RESERVATION_BEGIN);
            mDateView.setText(
                    Utility.getDayName(context, begin) + ", " +
                    Utility.getFormattedMonthDay(context, begin));

            // End time
            String end = data.getString(COL_RESERVATION_END);

            // Set begin, end and duration
            mBeginEndDurationView
                    .setText(Utility.formatBeginEndDuration(context, begin, end));

            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    context.getString(R.string.reservation_details_created_datetime_format));

            // Creation datetime and user name
            String created = data.getString(COL_RESERVATION_CREATED);
            String userName = data.getString(COL_USER_NAME);

            mCreatedView.setText(
                    String.format(
                            getActivity().getString(R.string.reservation_details_created),
                            userName,
                            dateFormat.format(RoomsContract.getDateTimeFromDb(created))));

            // Set fields used by actions
            String phoneNumber = data.getString(COL_USER_PHONE_NUMBER);
            String email = data.getString(COL_USER_EMAIL);
            mUserName = userName;
            mUserPhoneNumber = phoneNumber;
            mUserEmail = email;
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) { }
}
